﻿using System;
using System.Data;
using System.Text;
using Microsoft.ApplicationBlocks.Data;

using umbraco.cms.businesslogic.datatype;

namespace ProlificNotion.Umbraco.DataTypes
{
    /// <summary>
    /// A revised member picker datatype for Umbraco that allows the list to be filtered
    /// </summary>
    public class FilteredMemberPickerDataType : AbstractDataEditor
    {
        private FilteredMemberPickerPreValueEditor fmpPreValueEditor;
        private FilteredMemberPicker fmp = new FilteredMemberPicker();

        /// <summary>
        /// Initializes a new instance of the <see cref="FilteredMemberPickerDataType"/> class.
        /// </summary>
        public FilteredMemberPickerDataType()
        {
            base.RenderControl = fmp;
            base.DataEditorControl.OnSave += new umbraco.cms.businesslogic.datatype.AbstractDataEditorControl.SaveEventHandler(DataEditorControl_OnSave);
            fmp.Init += new EventHandler(fmp_DataBind);
            fmp.DataBound += new EventHandler(fmp_DataBound);

            fmp.DataTextField = "memberName";
            fmp.DataValueField = "memberId";
        }
       
        /// <summary>
        /// Gets the id.
        /// </summary>
        /// <value>The id.</value>
        public override Guid Id
        {
            get
            {
                return new Guid("7bdb5b17-c4b5-4cd3-9564-6b110648a605");
            }
        }

        /// <summary>
        /// Gets the name of the data type.
        /// </summary>
        /// <value>The name of the data type.</value>
        public override string DataTypeName
        {
            get
            {
                return "Filtered Member Picker";
            }
        }

        /// <summary>
        /// Gets the prevalue editor.
        /// </summary>
        /// <value>The prevalue editor.</value>
        public override umbraco.interfaces.IDataPrevalue PrevalueEditor
        {
            get
            {
                if (fmpPreValueEditor == null)
                {
                    fmpPreValueEditor = new FilteredMemberPickerPreValueEditor(this);
                }
                return fmpPreValueEditor;
            }
        }

        /// <summary>
        /// Handles the DataEditorControl OnSave event
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DataEditorControl_OnSave(EventArgs e)
        {
            Int32 mid = 0;
            if (Int32.TryParse(fmp.SelectedValue, out mid))
            {
                base.Data.Value = mid;
            }
        }

        /// <summary>
        /// Handles the DataBind event of the fmp control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void fmp_DataBind(object sender, EventArgs e)
        {
            string[] filters = ((FilteredMemberPickerPreValueEditor)PrevalueEditor).Filters;

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(@"SELECT     d.contentNodeId AS memberId, n.text AS memberName{0}", Environment.NewLine);
            sb.AppendFormat(@"FROM         cmsPropertyType AS t INNER JOIN{0}", Environment.NewLine);
            sb.AppendFormat(@"                      cmsPropertyData AS d ON t.id = d.propertytypeid INNER JOIN{0}", Environment.NewLine);
            sb.AppendFormat(@"                      umbracoNode AS n ON d.contentNodeId = n.id RIGHT OUTER JOIN{0}", Environment.NewLine);
            sb.AppendFormat(@"                      cmsMember2MemberGroup ON d.contentNodeId = cmsMember2MemberGroup.Member{0}", Environment.NewLine);
            
            //- Determine if we need to add a WHERE clause
            if (filters.Length > 0)
            {
                sb.AppendFormat(@"WHERE {0}", Environment.NewLine);
            }

            //- Add the filters
            if (filters.Length == 1)
            {
                sb.Append("(cmsMember2MemberGroup.MemberGroup = " + filters[0] + ")");
            }
            else if (filters.Length > 1)
            {
                foreach (string s in filters)
                {
                    sb.Append("(cmsMember2MemberGroup.MemberGroup = " + filters[0] + ") OR ");
                }
                //- Remove the trailing OR
                sb.Remove(sb.Length - 3, 3);
            }
            sb.AppendFormat(@"GROUP BY d.contentNodeId, n.text");
            sb.AppendLine(" ORDER BY n.text");

            fmp.DataSource = SqlHelper.ExecuteDataset(umbraco.GlobalSettings.DbDSN, CommandType.Text, sb.ToString());
            fmp.DataBind();
        }


        /// <summary>
        /// Handles the DataBound event of the fmp control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void fmp_DataBound(object sender, EventArgs e)
        {
            fmp.Items.Insert(0, "Please select...");

            if (base.Data.Value != null)
            {
                if (fmp.Items.FindByValue(base.Data.Value.ToString()) != null)
                {
                    fmp.Items.FindByValue(base.Data.Value.ToString()).Selected = true;
                }
            }
        }
    }
}
